var AjaxCrud = QualityCheck.AjaxCRUD;
var serverUrl = QualityCheck.GPUD.ServiceConfig;
var map = null;
var toolbar = null;
var scale = null;
var pointMarker = {};
var poly = {};
var circle = {};
var currentPage = 1;
var pageSize = 10;
var style = {
        color:'#FC740F',
        fillColor:'#FC740F',
        fillOpacity:0.2,
        weight:3
    };
var style1 = {
        color:'red',
        fillColor:'blue',
        fillOpacity:0.2,
        weight:3
    };
var style2 = {
        color:'blue',
        fillColor:'yellow',
        fillOpacity:0.2,
        weight:3
    };
var style3 = {
        color:'blue',
        fillColor:'red',
        fillOpacity:0.2,
        weight:3
    };
$(function(){
	var usercode = $("#user-name",parent.parent.document).attr("code");
	var userkey = $("#user-name",parent.parent.document).attr("key");
	var usertype = $("#user-name",parent.parent.document).attr("usertype");
	keyCheck(usercode,usertype,userkey,function(){
		initPages();
		window.onresize = function () {
			initPages();
		};
		initTime();
		pageBtns();
		initMap();
		getSosInfo(currentPage,pageSize);
		getSchoolFence();
	});
});
function initTime(){
	var date = new Date();
	var newDate = getFormatDate(date,"yyyy-MM-dd hh:mm");
	var startTime = getFormatDate(new Date(date.getTime()-1000*60*60*24),"yyyy-MM-dd ");
	$("#startTime").val(startTime+"00:00");
	$("#endTime").val(newDate);
}
function initMap(){
	map = new AMap.Map("map",{
		level:15,//设置地图缩放级别
	});
	map.plugin(["AMap.ToolBar","AMap.OverView","AMap.Scale"],function(){ 
		toolbar = new AMap.ToolBar();
		toolbar.autoPosition=false; //加载工具条 
		map.addControl(toolbar);  	
		scale = new AMap.Scale(); //加载比例尺
		map.addControl(scale);
	});
	map.setDefaultCursor("url(http://developer.amap.com/wp-content/uploads/2014/06/closedhand.cur),pointer");
	$(".amap-logo").hide();
	$(".amap-copyright").hide();
	$(".amap-container").css("position","absolute");
}
function getNowCity(){
	  //加载城市查询插件
    AMap.service(["AMap.CitySearch"], function() {
        //实例化城市查询类
        var citysearch = new AMap.CitySearch();
        //自动获取用户IP，返回当前城市
        citysearch.getLocalCity(function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
                if (result && result.city && result.bounds) {
                    var citybounds = result.bounds;
                    //地图显示当前城市
                    map.panTo(new AMap.LngLat(citybounds.getCenter().lng,citybounds.getCenter().lat));
                }
            }
        });
    });
}
function getSosInfo(currentpage,pagesize){
	var userKey = $("#user-name",parent.parent.document).attr("key");
	var usertype = $("#user-name",parent.parent.document).attr("usertype");
	var starttime = strToDate($("#startTime").val()+"00")/1000;
	var endtime = strToDate($("#endTime").val()+"59")/1000;
	var studentCode = $(".students-choice-select",parent.document).attr("studentcode");
	var flag = $(".search-model-select").attr("model");
	var data = {
			cmd:"getSosWarn",
			model:"position",
			userKey:userKey,
			data:{
				startTime:starttime,
				endTime:endtime,
				studentcode:studentCode,
				usertype: usertype,
				currentpage:currentpage,
				pageSize:pagesize,
				flag: flag,
			},
			remark:"",
			
	};
	map.clearInfoWindow();
	debugger;
	AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
		var content = "";
		var content1 = "";
		for(var key in pointMarker){
			if(pointMarker[key]){
				pointMarker[key].setMap(null);
			}
		}
		if(res.result == 1 && res.data != undefined && res.data != ""){
			var data = res.data.list;
			var total = res.data.total;
			totalPage = Math.ceil(total/pageSize);
			$("#total-page").text(totalPage);
			$("#now-page").text(currentpage);
			if(data.length > 0){
				for(var i = 0; i < data.length; i++){
					for(var key in data[i]){
						if(data[i][key] == null || data[i][key] == undefined){
							data[i][key] = "";
						}
					}
					content += "<div class=\"data-trs-show\" data = '"+JSON.stringify(data[i])+"'>" +
									"<div class=\"pdata-name\" title='"+data[i].studentname+"' style='width:180px;'>"+substr(data[i].studentname,13)+"</div>" +
									"<div class=\"pdata-class\" style='font-size:12px;width:180px;'>"+ getFormatDateByLong(parseInt(data[i].time)*1000,"yyyy-MM-dd hh:mm:ss") + "</div>" +
									"<div class=\"pdata-add\" title=\""+data[i].address+"\" style='width:180px;'>" + substr(data[i].address,13) + "</div>" +
								"</div>";
//					if(data[i].flag == 0){
//						content += "<div class=\"data-trs-show\" data = '"+JSON.stringify(data[i])+"'>" +
//										"<div class=\"pdata-name\" title='"+data[i].studentname+"'>"+substr(data[i].studentname,5)+"</div>" +
//										"<div class=\"pdata-img\">" +
//											"<div class='pdata-flag' style='color:red;'>未处理</div>" +
//										"</div>" +
//										"<div class=\"pdata-class\" style='font-size:12px;'>"+ getFormatDateByLong(parseInt(data[i].time)*1000,"yyyy-MM-dd hh:mm:ss") + "</div>" +
//										"<div class=\"pdata-add\" title=\""+data[i].address+"\">" + substr(data[i].address,9) + "</div>" +
//									"</div>";
//					}else{
//						content1 += "<div class=\"data-trs-show\" data = '"+JSON.stringify(data[i])+"'>" +
//										"<div class=\"pdata-name\" title='"+data[i].studentname+"'>"+substr(data[i].studentname,5)+"</div>" +
//										"<div class=\"pdata-img\">" +
//											"<div class='pdata-flag' style='color:#b5b5b5;'>已处理</div>" +
//										"</div>" +
//										"<div class=\"pdata-class\" style='font-size:12px;'>"+ getFormatDateByLong(parseInt(data[i].time)*1000,"yyyy-MM-dd hh:mm:ss") + "</div>" +
//										"<div class=\"pdata-add\" title=\""+data[i].address+"\">" + substr(data[i].address,9) + "</div>" +
//									"</div>";
//					}
					if(i == 0){
						if(res.data.list[0].lonLat != ""){
							var pointArr = data[i].lonLat.split(",");
							var y = pointArr[0];
							var x = pointArr[1];
							var pointObj = getPointObj(data[i]);
							var icon = new AMap.Icon({
								size:new AMap.Size(40,40),//图标大小
								image:pointObj.imgUrl,//大图地址
								imageSize:new AMap.Size(40,40)
							});
							addMarker(x,y,icon,pointObj.showObj,"sospoint");
							map.panTo(new AMap.LngLat(y,x));
						}
					}
				}
				$(".left-datas-show").empty();
				$(".left-datas-show").append(content);
//				var sostype = $("#sos-type option:selected").val();
//				$(".left-datas-show").empty();
//				if(sostype==""){
//					if(content == "" && content1 == ""){
//						content = "<div class='no-res-show'>未查询到相关数据！</div>";
//					}
//					$(".left-datas-show").append(content);
//					$(".left-datas-show").append(content1);
//				}else if(sostype=="1"){
//					if(content == ""){
//						content = "<div class='no-res-show'>未查询到相关数据！</div>";
//					}
//					$(".left-datas-show").append(content);
//				}else if(sostype=="2"){
//					if(content1 == ""){
//						content1 = "<div class='no-res-show'>未查询到相关数据！</div>";
//					}
//					$(".left-datas-show").append(content1);
//				}
				$(".data-trs-show").unbind("click");
				$(".data-trs-show").click(function(){
					var data = JSON.parse($(this).attr("data"));
					var lonLat = data.lonLat;
					var pointArr = lonLat.split(",");
					var y = pointArr[0];
					var x = pointArr[1];
					var id = data.id;
					var flag = data.flag;
					var pointObj = getPointObj(data);
					var icon = new AMap.Icon({
						size:new AMap.Size(40,40),//图标大小
						image:pointObj.imgUrl,//大图地址
						imageSize:new AMap.Size(40,40)
					});
					addMarker(x,y,icon,pointObj.showObj,"sospoint");
					map.panTo(new AMap.LngLat(y,x));
					showDialogMes(pointObj.showObj,id,flag);
					$(".data-trs-show").removeClass("data-trs-show-selected");
					$(this).addClass("data-trs-show-selected");
//					if(flag == 0){
//						updateStudentSos(id);
//					}else{
//						alertBox("already-done","已处理",false);
//					}
				});
				
			}else{
				content += "<div class='no-res-show'>未查询到相关数据！</div>";
				$(".left-datas-show").empty();
				$(".left-datas-show").append(content);
				getNowCity();
			}
		}else{
			content += "<div class='no-res-show'>查询服务出错了！</div>";
			$(".left-datas-show").empty();
			$(".left-datas-show").append(content);
			getNowCity();
		}
	},null,null);
}
function getPointObj(data){
	var pointObj = {};
	var showObj = {};
	showObj["姓名"] = data.studentname;
	showObj["IMEI"] = data.imei;
	showObj["报警时间"] = getSmpFormatDateByLong(parseInt(data.time)*1000,true);
	if(data.address != null){
		showObj["当前位置"] = data.address;
	}else{
		showObj["当前位置"] = "暂时不能定位到准确地点";
	}
	if(data.remark == 0 && data.remark == "0"){
		showObj["报警方式"] = "正常";
	}else if(data.remark == 1 && data.remark == "1"){
		showObj["报警方式"] = "开机报警";
	}else if(data.remark == 2 && data.remark == "2"){
		showObj["报警方式"] = "低电报警";
	}else if(data.remark == 3 && data.remark == "3"){
		showObj["报警方式"] = "紧急呼叫";
	}else if(data.remark == 4 && data.remark == "4"){
		showObj["报警方式"] = "进入电子围栏";
	}else if(data.remark == 5 && data.remark == "5"){
		showObj["报警方式"] = "出电子围栏";
	}else if(data.remark == 6 && data.remark == "6"){
		showObj["报警方式"] = "关机报警";
	}else if(data.remark == 8 && data.remark == "8"){
		showObj["报警方式"] = "超速报警";
	}else if(data.remark == 9 && data.remark == "9"){
		showObj["报警方式"] = "GPS 进入盲区报警";
	}else if(data.remark == 10 && data.remark == "10"){
		showObj["报警方式"] = "GPS 离开盲区报警";
	}else if(data.remark == 11 && data.remark == "11"){
		showObj["报警方式"] = "非法使用报警";
	}else{
		showObj["报警方式"] = "--";
	}
	var imgUrl = "";
	if(data.type == 0 || data.type == "0"){
		imgUrl = '../../../../img/position/lixian.png';
		showObj["定位方式"] = "离线";
	}else if(data.type == 1 || data.type == "1"){
		imgUrl = '../../../../img/position/beidou.png';
		showObj["定位方式"] = "北斗定位";
	}else if(data.type == 2 || data.type == "2"){
		imgUrl = '../../../../img/position/shinei.png';
		showObj["定位方式"] = "蓝牙定位";
	}else if(data.type == 3 || data.type == "3"){
		imgUrl = '../../../../img/position/jizhan.png';
		showObj["定位方式"] = "基站定位";
	}
	pointObj["imgUrl"] = imgUrl;
	pointObj["showObj"] = showObj;
	return pointObj;
}
function showDialogMes(objs,id,flag){	
	var contents = "<table class='psos-dialog-table'>" + "<div class='psos-dialog-close'>X</div>"+
	"<tr><td class='table-psos-td1'>姓名  : </td><td class='table-psos-td2'>" + objs["姓名"] + "</td></tr>" +
	"<tr><td class='table-psos-td1'>IMEI : </td><td class='table-psos-td2'>" + objs["IMEI"] + "</td></tr>" +
	"<tr><td class='table-psos-td1'>报警时间  : </td><td class='table-psos-td2'>" + objs["报警时间"] + "</td></tr>"+
	"<tr><td class='table-psos-td1'>报警方式  : </td><td class='table-psos-td2'>" + objs["报警方式"] + "</td></tr>" +
	"<tr><td class='table-psos-td1'>定位方式  : </td><td class='table-psos-td2'>" + objs["定位方式"] + "</td></tr>" +
	"<tr><td class='table-psos-td1'>报警位置  : </td><td class='table-psos-td2'>" + objs["当前位置"] + "</td></tr>" +
	"</table><div class='fence-edit-save' id='know-flag'>知道了</div>";
	$("#sos-dialog").empty();
	$("#sos-dialog").append(contents);
	$("#sos-dialog").show();
	if(flag == 1){
		$("#know-flag").hide();
		$(".psos-dialog-table").css({"margin":"0 auto 30px"});
	}else{
		$("#know-flag").show();
		$(".psos-dialog-table").css({"margin":"0 auto"});
	}
	$("#know-flag").unbind("click");
	$("#know-flag").click(function(){
		updateStudentSos(id);
		$("#sos-dialog").hide();
	});
	$(".psos-dialog-close").unbind("click");
	$(".psos-dialog-close").click(function(){
		$("#sos-dialog").hide();
		$(".data-trs-show").removeClass("data-trs-show-selected");
	});
}
function pageBtns(){
	$(".sos-search-btn").click(function(){
		getSosInfo(1,pageSize);
	});
	$("#last-page").click(function(){
		if(currentPage > 1){
			currentPage --;
			getSosInfo(currentPage,pageSize);
		}else{
			return false;
		}
	});
	$("#next-page").click(function(){
		if(currentPage < totalPage){
			currentPage ++;
			getSosInfo(currentPage,pageSize);
		}else{
			return false;
		}
	});
	var timers = null;
	$(".search-model").click(function(){
		$(".search-model").removeClass("search-model-select");
		$(this).addClass("search-model-select");
		$("#sos-dialog").hide();
		currentPage = 1;
		getSosInfo(currentPage,pageSize);
//		var model = $(this).attr("model");
//		if(model == 0){
//			getNowSosInfo();
//			$(".search-top-time").animate({"height":"0px"},function(){
//				$(".search-top-time input").hide();
//				var leftDH = $(".left-data-show").height() - $(".search-top-time").height() - $(".left-datas-page").height() - $(".left-search-data").height() - 25;
//				$(".left-datas-show").animate({"height":leftDH+"px"},function(){
//					timers = window.setInterval(function(){
//						getNowSosInfo();
//					}, 60000);
//				});
//			});
//			$(".sos-search-btn").animate({"height":"0px"});
//		}else if(model == 1){
//			$(".search-top-time").animate({"height":"60px"},function(){
//				$(".search-top-time input").show();
//				var leftDH = $(".left-data-show").height() - $(".search-top-time").height() - $(".left-datas-page").height() - $(".left-search-data").height() - 25;
//				$(".left-datas-show").animate({"height":leftDH+"px"});
//				window.clearInterval(timers);
//			});
//			$(".sos-search-btn").animate({"height":"60px"});
//			var date = new Date();
//			var newDate = getFormatDate(date,"yyyy-MM-dd");
//			$("#startTime").val(newDate + " 08:00");
//			$("#endTime").val(newDate + " 23:00");
//		}
	});
	$(".students-choice",parent.document).unbind("click");
	$(".students-choice",parent.document).click(function(){
		$(".students-choice",parent.document).removeClass("students-choice-select");
		$(this).addClass("students-choice-select");
		$("#sos-dialog").hide();
		getSosInfo(currentPage,pageSize);
		getSchoolFence();
	});
	
}
function updateStudentSos(id){
	var userKey = $("#user-name",parent.parent.document).attr("key");
	var data = {
			cmd:"updateSosWarn",
			model:"position",
			userKey:userKey,
			data:{
				id:id,
				flag:1
			},
			remark:"",
	};
	processBegin("设置成已查看");
	AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
		if(res.result == 1){
			processEnd("设置查看成功");
			closeDialog(function(){
				getSosInfo(currentPage,pageSize);
			});
		}
	},null,null);
}
function getSchoolFence(){
	var userKey = $("#user-name",parent.parent.document).attr("key");
	var studentCode = $(".students-choice-select",parent.document).attr("studentcode");
	var data = {
			cmd:"getSchoolFenceByStudentCode",
			model:"fence",
			userKey:userKey,
			data:{
				studentcode:studentCode
			},
			remark:""
	};
	AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
		for(var key in circle){
			circle[key].setMap(null);
		}
		circle = {};
		if(res.result == 1 && res.data != undefined && res.data != ""){
			var fencepoint = res.data.center.split(",");
			var x = fencepoint[0] * 1;
			var y = fencepoint[1] * 1;
			var fenceradius = res.data.radius;
			addCircle("schoolfence",new AMap.LngLat(x,y),fenceradius*100,style);
		}else{
			processError("学校围栏加载失败！");
		}
		getStudentFence(userKey,studentCode);
	},null,null);
}
function getStudentFence(userKey,studentCode){
	processBegin("数据加载中···");
	var data = {
			cmd:"getFenceByStudentCode",
			model:"fence",
			userKey:userKey,
			data:{
				studentcode:studentCode
			},
			remark:""
	};
	AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
		for(var key in circle){
			if(key != "schoolfence"){
				circle[key].setMap(null);
			}
		}
		if(res.result == 1){
			processEnd("数据加载成功");
			var list = res.data;
			for(var i = 0; i < list.length; i++){
				var latlngStr = list[i].fencepoint;
				var listArr = latlngStr.split(",");
				if(list[i].type == 1){
					addCircle(list[i].fencecode,new AMap.LngLat(listArr[0]*1,listArr[1]*1),list[i].fenceradius*1,style1);
				}else if(list[i].type == 2){
					addCircle(list[i].fencecode,new AMap.LngLat(listArr[0]*1,listArr[1]*1),list[i].fenceradius*1,style2);
				}else if(list[i].type == 2){
					addCircle(list[i].fencecode,new AMap.LngLat(listArr[0]*1,listArr[1]*1),list[i].fenceradius*1,style3);
				}
				
			}
		}else{
			processError("学生围栏加载失败！");
		}
	},null,null);
}
function getNowSosInfo(){
	var date = new Date();
	var earlyDate = getFormatDate(date,"yyyy-MM-dd");
	var newDate = getFormatDate(date,"yyyy-MM-dd hh:mm:ss");
	$("#startTime").val(earlyDate + " 06:00:00");
	$("#endTime").val(newDate);
	getSosInfo(1,pageSize);
}
//添加点方法并注册线点击事件
function addMarker(x,y,icon,obj,name){
	if(pointMarker[name]){
		pointMarker[name].setMap(null);
	}
	pointMarker[name] = new AMap.Marker({
		id:name,
		position:new AMap.LngLat(y,x),
		icon:icon, //marker图标
		offset:{x:-20,y:-40} //相对于基点的位置
	});
	pointMarker[name].setMap(map);
	    clickLayer(pointMarker[name],function(){
	    	var content = "<table>";
	    for(key in obj){
	    	if(key == "数据时间"){
	    		if(obj[key].toString().indexOf("-") < 0){
	    			obj[key] = getSmpFormatDateByLong(parseInt(obj[key])*1000,true);
	    		}
	    	}
	        content += "<tr><td style='text-align: right;font-weight:700;width:35%;font-size:15px;'>"+key+"：</td><td style='font-size:15px;'>"+obj[key]+"</td></tr>";
	    }
	    content += "</table>";
	    map.clearInfoWindow();
	    var inforWindow = new AMap.InfoWindow({
			offset:new AMap.Pixel(0,-26),
			content:content
		});
	    inforWindow.open(map,pointMarker[name].getPosition());
	    });
}
function addPolygon(name,latlngs,options){
	if(poly[name]){
		map.remove(poly[name]);
	}
	poly[name] = new AMap.Polygon({
		id:name,//多边形ID
		path:latlngs,//多边形顶点经纬度数组
		strokeColor:options.color,//线颜色
		strokeWeight:3,	//线宽
		fillColor: options.fillColor,//填充色
		fillOpacity: 0.2 //填充透明度
	});
	poly[name].setMap(map);
}
function addCircle(name,latlng,radius,options){
	if(circle[name]){
		map.remove(circle[name]);
	}
	circle[name] = new AMap.Circle({
		id:name,
		center:latlng,//圆心，基点
		radius:radius,//半径
		strokeColor: options.color,//线颜色
		strokeOpacity: 1,//线透明度
		strokeWeight: 3,//线宽
		fillColor: options.fillColor,//填充颜色
		fillOpacity: 0.2//填充透明度
	});
	circle[name].setMap(map);
}
function clickLayer(layer,method){
	AMap.event.addListener(layer, "click", method);
}
function substr(str,len){
	if(str != undefined){
		if(str.length > len){
			str = str.substring(0,len-2)+"...";
			return str;
		}else{
			return str;
		}
	}else{
		return "";
	}
}
function initPages(){
	var bodyRW = $("#aposition-body",parent.document).width() - $(".left-data-show").width();
	$("#map").width(bodyRW);
	
	var leftDH = $(".left-data-show").height() - $(".search-top-time").height() - $(".left-datas-page").height() - $(".left-search-data").height() - 25;
	$(".left-datas-show").height(leftDH);
}